//
//  HFEmoticonKeyBoardView.swift
//  sinaMicroBlog
//
//  Created by mac on 15/11/21.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

private let EmoticonCellId = "EmoticonCellId"
private let toolBarHeight: CGFloat = 36
class HFEmoticonKeyBoardView: UIView {
    
    var SelectEmoticon: ((emoticon: HFEmoticon) -> ())?
    
    private var packages = HFEmoticonManager().packages
   
    init(SelectEmoticon: (emoticon: HFEmoticon) -> ()){
        
        let rect = CGRectMake(0, 0, screenW, 220)
        super.init(frame: rect)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载所有控件
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var colloctionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        //大小,行距,列距,组距,滚动方向
        let itemLength = screenW / 7
        layout.itemSize = CGSize(width: itemLength, height: itemLength)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let margin = (self.bounds.height - 3 * itemLength - toolBarHeight) / 4
        layout.sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        let colloctionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        //cell设置
        return colloctionView
    }()

}

extension HFEmoticonKeyBoardView {
    
    private func setupUI() {
        //添加视图
        addSubview(toolBar)
        addSubview(colloctionView)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self)
            //设置高度
            make.height.equalTo(toolBarHeight)
        }
        
        colloctionView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        //设置工具条
        setupToolBar()
    }
    
    
    //设置toolbar
    private func setupToolBar() {
        
        //设置 toolbar 文本渲染颜色
        toolBar.tintColor = UIColor.lightGrayColor()
        
        //声明items数组
        var items = [UIBarButtonItem]()
        //定义一个变量  来标识item的tag
        var index = 0
        for package in packages {
            let item = UIBarButtonItem(title:package.group_name_cn , style: .Plain, target: self, action: "itemClick:")
            //添加元素
            items.append(item)
            items.last?.tag = index++
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        //移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
}
